<template>
  <div class="table-main">
    <h1>{{title}}</h1>
    <el-table :data="tableData"
              border
              height="4rem"
              style="width:10rem;">
      <el-table-column v-for="title in titleList"
                       fit
                       :prop="title.name"
                       :key="title.name"
                       :label="title.description?title.description:title.name">
      </el-table-column>
    </el-table>
  </div>

</template>
<script>
export default {
  name: 'TableComponent',
  props: ['chartData', 'chartTitle'],
  mounted () {
    let self = this;
    self.init(self.chartData);
    self.updateTitle(self.chartTitle)
    self.$on('updateData', self.init)
    self.$on('updateTitle', self.updateTitle)
  },
  data () {
    return {
      title: '',
      titleList: [],
      tableData: [
        //   {
        //   date: '2016-05-03',
        //   name: '王小虎',
        //   province: '上海',
        //   city: '普陀区',
        //   address: '上海市普陀区金沙江路 1518 弄',
        //   zip: 200333
        // }
      ]
    }
  },
  methods: {
    init (chartData) {
      console.log('chartData', chartData);
      let self = this
      self.titleList = []
      self.tableData = []
      if (chartData && JSON.stringify(chartData) != "{}") {
        let xTitle = Object.assign([], chartData.xTitle)
        let yTitle = chartData.yTitle.map(function (item) { return { name: item.name, description: item.description } });
        let xFieldData = Object.assign([], chartData.xFieldData)
        let yFieldData = Object.assign([], chartData.yFieldData)
        let keyNames = [];
        for (let i = 0; i < xTitle.length; i++) {
          if (xTitle[i].description == '') xTitle[i].description == xTitle[i].name;
          self.titleList.push(xTitle[i]);
          keyNames.push(xTitle[i].name);
        }
        for (let i = 0; i < yTitle.length; i++) {
          if (yTitle[i].description == '') yTitle[i].description == yTitle[i].name;
          self.titleList.push(yTitle[i]);
          keyNames.push(yTitle[i].name);
        }
        console.log(keyNames);
        console.log(xFieldData);
        console.log(yFieldData);
        for (let i = 0; i < xFieldData.length; i++) {
          let temp = { [keyNames[0]]: xFieldData[i] }
          self.tableData.push(temp);
        }
        for (let i = 0; i < yFieldData.length; i++) {
          for (let j = 0; j < yFieldData[i].length; j++) {
            // console.log(keyNames[i + 1]);
            // console.log(yFieldData[i][j]);
            self.tableData[j][keyNames[i + 1]] = yFieldData[i][j];
          }
        }
        console.log(self.titleList);
        console.log(self.tableData);
      }
    },
    updateTitle (value) {
      this.title = value
    }
  }
}
</script>
<style lang="stylus" scoped>
h1
  font-weight bold
</style>